import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/common/count_text.dart';
import 'package:material_collection_app/widget/common/empty_tips.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:material_collection_app/widget/common/tabbar_custom_return.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class CheckDetailPage extends StatefulWidget {
  final Map arguments;

  CheckDetailPage({Key key, this.arguments}) : super(key: key);

  @override
  State<StatefulWidget> createState() => MyState();
}

class MyState extends State<CheckDetailPage> {
  Map detailInfo;
  bool detailLoadSuccess = false;
  List<String> tabs = ['盘点详情', '盘点进度'];

  List proList = [];
  int proCurrentPage = 1;
  int proLastPage = 1;
  bool proLoadSuccess = false;
  List resultList = [];
  List resultAllList = [];

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  //页面无数据的刷新控件
  RefreshController _emptyRefreshController =
      RefreshController(initialRefresh: false);

  //container的刷新控件
  RefreshController _containerRefreshController =
      RefreshController(initialRefresh: false);

  @override
  void initState() {
    super.initState();
    getDetail();
    getProgress();

    if (widget.arguments['status'] == '20') {
      getResult();
      tabs.add('盘点结果');
    }
  }

  // 获取盘点详情
  void getDetail({bool loadMore = false}) async {
    setState(() {
      detailLoadSuccess = false;
    });
    DioUtils.request("InventoryTask/getDetails",
        context: context,
        method: "POST",
        params: {'id': widget.arguments['item']['id']}, onSuccess: (res) {
      if (res['code'] == 1) {
        if (mounted) {
          setState(() {
            detailInfo = res['data'];
            detailLoadSuccess = true;
          });
        }
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 获取盘点结果
  void getResult({bool loadMore = false}) async {
    setState(() {
      detailLoadSuccess = false;
    });
    DioUtils.request("InventoryTask/getMaterialList",
        context: context,
        method: "POST",
        params: {'id': widget.arguments['item']['id']}, onSuccess: (res) {
      if (res['code'] == 1) {
        setState(() {
          resultAllList = res['data'];
        });

        filterRequltData();
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 获取盘点进度
  void getProgress({bool loadMore = false}) async {
    setState(() {
      proLoadSuccess = false;
    });

    if (loadMore) {
      proCurrentPage++;
    } else {
      proCurrentPage = 1;
    }

    DioUtils.request("InventoryTask/process",
        context: context,
        method: "POST",
        params: {
          'id': widget.arguments['item']['id'],
          'current_page': proCurrentPage,
        }, onSuccess: (res) {
      if (res['code'] == 1) {
        if (mounted) {
          setState(() {
            if (loadMore) {
              proList.addAll(res["data"]["data"]);
            } else {
              proList = res["data"]["data"];
            }
            proCurrentPage = res['data']['current_page'];
            proLastPage = res['data']['last_page'];
            proLoadSuccess = true;
          });
        }
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  void filterRequltData() {
    List list = [];

    for (Map item in resultAllList) {
      //tabIndex: 1 - 全部 2 - 物资正确 3 - 物资有误 4 - 盘盈
      //"res_status": 1, =物资正确
      //"res_status": 3,  = 物资错误
      switch (tabIndex) {
        case 1:
          {
            list = resultAllList;
          }
          break;
        case 2:
          {
            if (item['res_status'] == 1) {
              list.add(item);
            }
          }
          break;
        case 3:
          {
            if (item['res_status'] == 3) {
              list.add(item);
            }
          }
          break;
        case 4:
          {
            if (item['res_status'] != 1 && item['res_status'] != 3) {
              list.add(item);
            }
          }
          break;
        default:
      }
    }

    setState(() {
      resultList = list;
    });
  }

  void _onRefresh() async {
    _refreshController.loadComplete();
    _emptyRefreshController.loadComplete();
    _containerRefreshController.loadComplete();
    getProgress();

    await Future.delayed(Duration(milliseconds: 600));
    _refreshController.refreshCompleted();
    _emptyRefreshController.refreshCompleted();
    _containerRefreshController.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(milliseconds: 300));

    if (proCurrentPage == proLastPage) {
      _refreshController.loadNoData();
      _containerRefreshController.loadNoData();
      return;
    }

    // 加载更多数据
    if (proCurrentPage < proLastPage) {
      getProgress(loadMore: true);
      _refreshController.loadComplete();
      _containerRefreshController.loadComplete();
    }
  }

  Widget _buildCardHead(title) {
    return Container(
      width: 680.w,
      height: 90.w,
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
          border:
              Border(bottom: BorderSide(width: 1, color: Color(0xFFF1F1F1)))),
      child: Text(
        title,
        style: TextStyle(
            color: Color(0xFF333333),
            fontSize: 16,
            fontWeight: FontWeight.bold),
      ),
    );
  }

  Widget _buildRowText(title, text, [Color color]) {
    return Padding(
      padding: EdgeInsets.fromLTRB(0, 15.w, 0, 15.w),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Text(title.toString(),
              style: TextStyle(color: Color(0xFF999999), fontSize: 14)),
          Container(
            width: 384.w,
            alignment: Alignment.centerRight,
            child: Text(text.toString(),
                textAlign: TextAlign.right,
                style: TextStyle(
                  color: color ?? Color(0xFF333333),
                  fontSize: 14,
                )),
          )
        ],
      ),
    );
  }

  String getStore(info) {
    String str = info['store'] != null ? (info['store']['store_name']) : '--';

    for (var i = 0; i < info['library'].length; i++) {
      Map item = info['library'][i];

      str += item['library_name'];

      if (i != info['library'].length - 1) {
        str += '、';
      }
    }

    return str;
  }

  Widget _buildPageOne() {
    if (detailLoadSuccess) {
      return SingleChildScrollView(
          padding: EdgeInsets.fromLTRB(25.w, 30.w, 25.w, 50.w),
          child: Container(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Offstage(
                  offstage: widget.arguments['status'] == '10' ? false : true,
                  child: SizedBox(
                    width: 160.w,
                    height: 56.w,
                    child: ElevatedButton(
                      onPressed: () {
                        Navigator.pushNamed(context, '/scan_result',
                            arguments: {
                              'page': 'check_page',
                              'id': detailInfo['id'],
                              'itemIndex': widget.arguments['itemIndex'],
                              'back': 2
                            });
                      },
                      child: Text(
                        '扫描库区',
                        style: TextStyle(color: Colors.white, fontSize: 14),
                      ),
                      style: ElevatedButton.styleFrom(
                        padding: EdgeInsets.symmetric(horizontal: 0),
                        backgroundColor: Color(0xFF297CFF),
                        shape: RoundedRectangleBorder(
                            borderRadius:
                                BorderRadius.all(Radius.circular(8.w))),
                      ),
                    ),
                  ),
                ),
                Container(
                  width: 700.w,
                  margin: EdgeInsets.only(top: 24.w),
                  padding: EdgeInsets.only(bottom: 34.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(20.w),
                  ),
                  child: Column(
                    children: <Widget>[
                      _buildCardHead('盘点信息'),
                      Container(
                        padding: EdgeInsets.fromLTRB(24.w, 20.w, 24.w, 0),
                        child: Column(
                          children: <Widget>[
                            _buildRowText('盘点名称', detailInfo['name']),
                            _buildRowText(
                                '盘点类型', detailInfo['inventory_type_text']),
                            _buildRowText('盘点区域', getStore(detailInfo)),
                            _buildRowText(
                                '盘点人员',
                                detailInfo['member'] != null
                                    ? detailInfo['member']['name']
                                    : '--'),
                            _buildRowText('盘点日期', detailInfo['end_time']),
                            _buildRowText('盘点状态', detailInfo['status_text'],
                                Color(0xFFF54745)),
                          ],
                        ),
                      )
                    ],
                  ),
                ),
                Container(
                  width: 700.w,
                  margin: EdgeInsets.only(top: 24.w),
                  padding: EdgeInsets.only(bottom: 34.w),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(20.w),
                  ),
                  child: Column(
                    children: <Widget>[
                      _buildCardHead('制单'),
                      Container(
                        padding: EdgeInsets.fromLTRB(24.w, 20.w, 24.w, 0),
                        child: Column(
                          children: <Widget>[
                            _buildRowText(
                                '制单人',
                                detailInfo['creator'] != null
                                    ? detailInfo['creator']['name']
                                    : '--'),
                            _buildRowText('制单时间', detailInfo['update_time']),
                            _buildRowText('备注', detailInfo['remark']),
                          ],
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          ));
    } else {
      return Container();
    }
  }

  int tabIndex = 1;

  Widget _buildButton(title, index) {
    return Container(
      margin: EdgeInsets.only(right: 20.w),
      child: SizedBox(
        height: 56.w,
        child: ElevatedButton(
          onPressed: () {
            setState(() {
              tabIndex = index;
            });
            filterRequltData();
          },
          child: Text(
            title,
            style: TextStyle(
                color: tabIndex == index
                    ? Colors.white
                    : Utils.hexToColor('#666666'),
                fontSize: 14),
          ),
          style: ElevatedButton.styleFrom(
            padding: EdgeInsets.symmetric(horizontal: 0),
            backgroundColor: tabIndex == index
                ? Utils.hexToColor('#297CFF')
                : Utils.hexToColor('#F5F3F3'),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.all(Radius.circular(60.w))),
          ),
        ),
      ),
    );
  }

  Widget _buildPageThree() {
    return Container(
        color: Utils.hexToColor('#F5F6FA'),
        // padding: EdgeInsets.fromLTRB(25.w, 23.w, 25.w, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            Container(
              height: 100.w,
              color: Colors.white,
              padding: EdgeInsets.fromLTRB(25.w, 0, 25.w, 0),
              child: Row(
                children: <Widget>[
                  _buildButton('全部', 1),
                  _buildButton('物资正确', 2),
                  _buildButton('物资有误', 3),
                  _buildButton('盘盈', 4),
                ],
              ),
            ),
            CountText(number: resultList.length),
            Expanded(
                // flex: 1,
                child: Container(
                    padding: EdgeInsets.fromLTRB(25.w, 23.w, 25.w, 0),
                    child: Refresh(
                        refreshController: _refreshController,
                        onRefresh: _onRefresh,
                        onLoading: _onLoading,
                        child: ListView.builder(
                            itemCount: resultList.length,
                            padding: EdgeInsets.only(bottom: 60.w),
                            itemBuilder: (BuildContext context, int index) {
                              Map item = resultList[index];

                              return InkWell(
                                onTap: () {},
                                child: Container(
                                  width: 700.w,
                                  height: 210.w,
                                  margin: EdgeInsets.only(bottom: 16.w),
                                  padding: EdgeInsets.fromLTRB(
                                      24.w, 25.w, 24.w, 0.w),
                                  decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.circular(20.w),
                                  ),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Padding(
                                        padding: EdgeInsets.only(bottom: 5.w),
                                        child: Text(
                                            item['goods_name'] != null
                                                ? item['goods_name']
                                                : "",
                                            style: TextStyle(
                                                color: Color(0xFF333333),
                                                fontSize: 15,
                                                fontWeight: FontWeight.bold)),
                                      ),
                                      Row(
                                        // mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: <Widget>[
                                          Container(
                                            width: 300.w,
                                            margin: EdgeInsets.only(top: 13.w),
                                            child: Text('物资分类：',
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                    color: Color(0xFF666666),
                                                    fontSize: 12,
                                                    height: 1)),
                                          ),
                                        ],
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Container(
                                            width: 300.w,
                                            margin: EdgeInsets.only(top: 13.w),
                                            child: Text(
                                                '物资数量：' +
                                                    item['enter_qty']
                                                        .toString(),
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                    color: Color(0xFF666666),
                                                    fontSize: 12,
                                                    height: 1)),
                                          ),
                                          Container(
                                            width: 300.w,
                                            margin: EdgeInsets.only(
                                                left: 30.w, top: 13.w),
                                            child: Text(
                                                '所属仓库：' +
                                                    (item['store_store_name'] !=
                                                            null
                                                        ? item[
                                                            'store_store_name']
                                                        : ""),
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                    color: Color(0xFF666666),
                                                    fontSize: 12,
                                                    height: 1)),
                                          ),
                                        ],
                                      ),
                                      Row(
                                        children: <Widget>[
                                          Container(
                                            width: 300.w,
                                            margin: EdgeInsets.only(top: 16.w),
                                            child: Text(
                                                '所属库区：' +
                                                    (item['storeLibrary__library_name'] !=
                                                            null
                                                        ? item[
                                                            'storeLibrary__library_name']
                                                        : ""),
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                    color: Color(0xFF666666),
                                                    fontSize: 12,
                                                    height: 1)),
                                          ),
                                          Container(
                                            width: 300.w,
                                            margin: EdgeInsets.only(
                                                left: 30.w, top: 13.w),
                                            child: Text(
                                                '所属库位：' +
                                                    (item['storeDetail__detail_code'] !=
                                                            null
                                                        ? item[
                                                            'storeDetail__detail_code']
                                                        : ""),
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                    color: Color(0xFF666666),
                                                    fontSize: 12,
                                                    height: 1)),
                                          ),
                                        ],
                                      ),
                                    ],
                                  ),
                                ),
                              );
                            }))))
          ],
        ));
  }

  Widget _buildPageTwo() {
    if (proLoadSuccess && proList.length == 0) {
      //无数据
      return EmptyTips(
        refreshController: _emptyRefreshController,
        onRefresh: _onRefresh,
      );
    }

    return Container(
        color: Colors.white,
        child: Refresh(
            refreshController: _containerRefreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
                itemCount: proList.length,
                // padding: EdgeInsets.only(bottom: 60.w),
                padding: EdgeInsets.fromLTRB(25.w, 30.h, 25.w, 0.h),
                itemBuilder: (BuildContext context, int index) {
                  var item = proList[index];

                  return InkWell(
                      onTap: () {},
                      child: Stack(
                        children: <Widget>[
                          Container(
                              width: 700.w,
                              margin: EdgeInsets.only(left: 20.w),
                              padding:
                                  EdgeInsets.fromLTRB(0.w, 0.w, 24.w, 40.h),
                              decoration: BoxDecoration(
                                  border: Border(
                                      left: BorderSide(
                                          color: Utils.hexToColor('#F2F2F2')))),
                              child: Stack(
                                children: <Widget>[
                                  Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    children: <Widget>[
                                      Row(
                                        children: <Widget>[
                                          Container(
                                            width: 630.w,
                                            margin: EdgeInsets.only(top: 10.w),
                                            padding: EdgeInsets.only(
                                                left: 43.w, bottom: 5.w),
                                            child: Text(
                                                item['role_name'] +
                                                    '、' +
                                                    item['user_name'] +
                                                    '、' +
                                                    item['content'],
                                                // child: Text('业务组、仓管员完成入库',
                                                maxLines: 1,
                                                overflow: TextOverflow.ellipsis,
                                                style: TextStyle(
                                                    color: Color(0xFF333333),
                                                    fontSize: 15,
                                                    fontWeight: FontWeight.bold,
                                                    height: 1)),
                                          ),
                                        ],
                                      ),
                                      Padding(
                                        padding: EdgeInsets.only(
                                            left: 40.w, top: 13.w),
                                        child: Text(item['create_time'],
                                            maxLines: 1000,
                                            overflow: TextOverflow.ellipsis,
                                            style: TextStyle(
                                                color: Color(0xFF666666),
                                                fontSize: 12,
                                                height: 1)),
                                      ),
                                    ],
                                  ),
                                ],
                              )),
                          Offstage(
                            offstage: index == 0 ? false : true,
                            child: Container(
                              width: 6.w,
                              height: 10.w,
                              color: Colors.white,
                              margin: EdgeInsets.fromLTRB(18.w, 0.w, 0, 0),
                            ),
                          ),
                          Container(
                            width: 28.w,
                            height: 28.w,
                            margin: EdgeInsets.fromLTRB(7.w, 10.w, 0, 0),
                            decoration: BoxDecoration(
                                color: Utils.hexToColor('#409EFF'),
                                borderRadius: BorderRadius.circular(32.w),
                                border: Border.all(
                                    color: Utils.hexToColor('#E0EFFF'),
                                    width: 2)),
                          ),
                        ],
                      ));
                })));
  }

  Widget _buildTabBarView() {
    if (widget.arguments['status'] == '10') {
      return TabBarView(children: <Widget>[
        _buildPageOne(),
        _buildPageTwo(),
      ]);
    } else {
      return TabBarView(children: <Widget>[
        _buildPageOne(),
        _buildPageTwo(),
        _buildPageThree(),
      ]);
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    return DefaultTabController(
        length: tabs.length,
        initialIndex: 0,
        child: Scaffold(
            appBar: AppBar(
                backgroundColor: Utils.hexToColor('#297CFF'),
                bottom: PreferredSize(
                  preferredSize: Size(double.infinity, 0),
                  child: TabBarCustomReturn(
                    tabs: tabs,
                    indicatorInsets: EdgeInsets.fromLTRB(26, 0, 26, 4),
                  ),
                )),
            body: _buildTabBarView()));
  }
}
